package pers.cz.business;

import cn.hutool.core.date.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import pers.cz.mapper.SystemJobMapper;
import pers.cz.mapper.TaskJobMapper;
import pers.cz.model.SystemJob;
import pers.cz.model.TaskJob;
import pers.cz.mybatisPlugin.PageRowBounds;
import pers.cz.pub.AbstractBusiness;
import pers.cz.pub.SequenceEnum;
import pers.cz.quartz.core.QuartzJobFactory;
import org.quartz.SchedulerException;

import java.util.List;

/**
 * 定时任务业务实现类
 * @program: PostGirl-panent
 * @description: TaskJobBusiness
 * @author: Cheng Zhi
 * @create: 2021-04-26 20:36
 **/
public class TaskJobBusiness extends AbstractBusiness {

    Logger logger = LoggerFactory.getLogger(TaskJobBusiness.class);

    /**
     * 添加定时调度任务
     * @param jobName
     * @param cron
     * @param testCaseIds
     * @param userId
     * @param userName
     * @return
     */
    public int addTaskJob(String jobName, String cron, String testCaseIds, Integer userId, String userName, String ext1,String ext2, String testCaseType) {

        Long soNbr = cPublicFunc.getSoNbr(SequenceEnum.JOB_SEQUENCE);
        TaskJob taskJob = new TaskJob();
        taskJob.setId(soNbr);
        taskJob.setJobName(jobName);
        taskJob.setCron(cron);
        taskJob.setContent(testCaseIds);
        taskJob.setUserId(userId);
        taskJob.setCreateName(userName);
        taskJob.setCreatedTime(DateUtil.date());
        taskJob.setJobSwitch(true);
        taskJob.setSchedule(0);
        taskJob.setType(0);
        taskJob.setJobType(testCaseType);
        int count = this.getMapper().getBean(TaskJobMapper.class).insert(taskJob);

        // 插入taskJob的同时还需要插入到systemJob
        SystemJob systemJob = new SystemJob();
        systemJob.setJobId(soNbr);

        if (testCaseType.equals("regression")) {
            orgTestCaseJob(systemJob, jobName, cron, testCaseIds, userId, userName, ext1, ext2, testCaseType);
        } else if (testCaseType.equals("customize")) {
            orgAutoTestCaseJob(systemJob, jobName, cron, testCaseIds, userId, userName, ext1, ext2, testCaseType);
        } else if (testCaseType.equals("customizeJob")) {
            orgCustomizeJob(systemJob, jobName, cron, testCaseIds, userId, userName, ext1, ext2, testCaseType);
        }
        this.getMapper().getBean(SystemJobMapper.class).insert(systemJob);
        systemJob.setUserId(userId);
        QuartzJobFactory.addJob(systemJob);
        return count;
    }

    private void orgTestCaseJob(SystemJob systemJob, String jobName, String cron, String testCaseIds, Integer userId, String userName, String ext1,String ext2, String testCaseType) {

        //systemJob.setJobName("TestCaseJob" + soNbr);
        systemJob.setJobName(jobName);
        systemJob.setTriggerName("TestCaseJob");
        systemJob.setCronExpression(cron);
        systemJob.setJobImplClass("pers.cz.job.TestCaseJob");
        systemJob.setJobParam(testCaseIds);
        systemJob.setExt1(ext1);
        systemJob.setExt2(ext2);

    }

    private SystemJob orgAutoTestCaseJob(SystemJob systemJob, String jobName, String cron, String testCaseIds, Integer userId, String userName, String ext1,String ext2, String testCaseType) {

        //systemJob.setJobName("TestCaseJob" + soNbr);
        systemJob.setJobName(jobName);
        systemJob.setTriggerName("AutoTestCaseJob");
        systemJob.setCronExpression(cron);
        systemJob.setJobImplClass("pers.cz.job.AutoTestCaseJob");
        systemJob.setJobParam(testCaseIds);
        systemJob.setExt1(ext1);
        systemJob.setExt2(ext2);

        return systemJob;
    }

    private SystemJob orgCustomizeJob(SystemJob systemJob, String jobName, String cron, String testCaseIds, Integer userId, String userName, String ext1,String ext2, String testCaseType) {

        systemJob.setJobName(jobName);
        systemJob.setTriggerName("CustomizeJob");
        systemJob.setCronExpression(cron);
        systemJob.setJobImplClass(testCaseIds);
        systemJob.setJobParam(testCaseIds);
        systemJob.setExt1(ext1);
        systemJob.setExt2(ext2);

        return systemJob;
    }
    /**
     * 根据任务名称查询所有的TaskJob
     * @param name
     * @return
     */
    public List<TaskJob> queryTaskJobByJobName(String name) {

        List<TaskJob> taskJobList = this.getMapper().getBean(TaskJobMapper.class).selectByJobName(name);

        return taskJobList;
    }

    /**
     * 分页查询所有任务
     * @param pageStart
     * @param pageLimit
     * @return
     */
    public List<TaskJob> queryAllTaskJobByPage(Integer pageStart, Integer pageLimit) {

        PageRowBounds pageRowBounds = new PageRowBounds(pageStart, pageLimit);
        List<TaskJob> taskJobList = this.getMapper().getBean(TaskJobMapper.class).selectAllTaskJobByPage(pageRowBounds);
        return taskJobList;
    }

    /**
     * 查询任务总数
     * @return
     */
    public Integer quertCountTaskJob() {

        int count = this.getMapper().getBean(TaskJobMapper.class).selectCountTaskJob();
        return count;
    }

    /**
     * 根据任务id修改开关状态
     * @param id
     * @param jobWitch
     * @return
     */
    public Integer updateTaskJobSwitch(Integer id, Boolean jobWitch) throws Exception {
        TaskJob taskJob = new TaskJob();
        taskJob.setId(Long.valueOf(id));
        taskJob.setJobSwitch(jobWitch); // updateByPrimaryKeySelective

        // 如果开关关闭，则需要修改system
        String JobName = this.getMapper().getBean(SystemJobMapper.class).selectByPrimaryKey(id).getJobName();
        if (!jobWitch) {
            QuartzJobFactory.pauserTrigger(JobName);
        } else {
            QuartzJobFactory.resumeTrigger(JobName);
        }


        int count = this.getMapper().getBean(TaskJobMapper.class).updateByPrimaryKeySelective(taskJob);
        return count;
    }

    /**
     * 根据任务id修改执行计划
     * @param id
     * @param jobCron
     * @return
     */
    public Integer updateTaskJobCron(Integer id, String jobCron, String jobName) {

        TaskJob taskJob = new TaskJob();
        taskJob.setId(Long.valueOf(id));
        taskJob.setCron(jobCron);
        int count = this.getMapper().getBean(TaskJobMapper.class).updateByPrimaryKeySelective(taskJob);

        // 修改的同时也要修改系统job
        SystemJob systemJob = new SystemJob();
        systemJob.setJobId(Long.valueOf(id));
        systemJob.setCronExpression(jobCron);
        this.getMapper().getBean(SystemJobMapper.class).updateByPrimaryKeySelective(systemJob);

        // 实时修改系统调度时间
        try {
            QuartzJobFactory.rescheduleJob(jobName, jobCron);
        } catch (SchedulerException e) {
            logger.error("修改系统调度时间失败！", e);
        }
        return count;
    }

    public Integer deleteTaskJob(Integer id) {
        int count = this.getMapper().getBean(TaskJobMapper.class).deleteByPrimaryKey(id);
        this.getMapper().getBean(SystemJobMapper.class).deleteByPrimaryKey(id);

        return count;
    }

    /**
     * 立即执行job
     * @param id
     * @return
     */
    public Integer startJobNow(Integer id) {

        SystemJob systemJob = this.getMapper().getBean(SystemJobMapper.class).selectByPrimaryKey(id);
        try {
            QuartzJobFactory.triggerJob(systemJob.getJobName());
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
        // 未实现
        return 1;
    }
}
